<script setup lang="jsx">

import {computed, getCurrentInstance, h, reactive, ref, watch} from "vue";
import shipment from "@/api/document/shipment";
import {onBeforeRouteLeave} from "vue-router";
import dictHelp from "@/utils/dicthelp.js";
import BatchActionModal from "@cps/actions/batchActionModal.vue";
import waybill from "@/api/document/waybill.js";
import ParcelList from "@/views/document/AddToWaybill/parcelList.vue";
import {getDictData} from "@/utils/crud/dict.js";
import { color } from "echarts";
const crudRef = ref()
const batchActionRef = ref()
/*
服务
地址编码
已标识
未标识
*/
const columns = [
  {dataIndex: 'keywords', title: '关键字', search: true,hide:true},
  {dataIndex: 'shipment_no', title: '运单号', search: true},
  {dataIndex: '', title: '地址编码', search: true},
  {
    dataIndex: 'status',
    title: '状态',
    formType: 'select',
    dict: {name: 'shipment_parcel_type', translation: true},
    search: true
  },
  {
    dataIndex: 'end_delivery_type',
    title: '末端派送方式',
    formType: 'select',
    dict: {name: 'endDeliveryType', translation: true},
    search: true
  },
  {dataIndex: '', title: '问题件'},
  {dataIndex: 'user_id', title: '用户', formType: 'select', dict: dictHelp.customer, search: true,multiple:true,virtualListProps: {height: 400,}},
  {
    title: "服务",
    dataIndex: "service_ids",
    formType: "tree-select",
    maxTagCount: 1,
    addDisplay: false,
    editDisplay: false,
    hide: true,
    search: true,
    dict: {url: 'logistics/serviceGroup/tree'},
    multiple: true,
    treeCheckable: true,
    treeProps:{virtualListProps: {height: 200,}},
    // getDictData('attrs',value,crudRef)
  },
  {
    dataIndex: 'service_id',
    title: '服务',
    formType: 'select',
    dict: dictHelp.service,
    searchFormType: 'select',
    multiple: true,
    treeProps:{virtualListProps: {height: 200,}},
    customRender: ({record}) => {
      if(record.admin_service_id && record.admin_service_id != record.service_id){
        return h('div', [
          h('span',{style:{color:'red'}},getDictData('service_id', record.admin_service_id,crudRef)),
          h('br'),
          h('span',{style:{"text-decoration": "line-through",color:'#999999'}},getDictData('service_id', record.service_id,crudRef)),
        ])
      }
      return getDictData('service_id', record.service_id,crudRef)
    }
  },
  // todo
  {
    dataIndex: 'country', title: '国家', customRender({record}) {
      return h('div', [
        h('span', record.address.country),
        h('br'),
        h('span', record.address.postcode)
      ]);
    }
  },
  // {dataIndex:'', title: '箱数'},
  {
    title: '箱数', dataIndex: 'parcel_count', formType: 'input', customRender({record}) {
      if (record.volume_weight.parcel_count == record.waybill_volume_weight?.parcel_count) {
        return record.volume_weight.parcel_count;
      }
      return <div
          class="text-red-600">{record.waybill_volume_weight?.parcel_count} / {record.volume_weight.parcel_count}</div>
    }
  },
  {dataIndex: 'volume_weight.actual_weight', title: '实重'},
  {dataIndex: 'volume_weight.actual_volume_weight', title: '材重'},
  {dataIndex: 'volume_weight.actual_volume', title: '体积'},
  {dataIndex: 'volume_weight.charge_weight', title: '收费重'},
  // todo 待补充
  {dataIndex: '', title: '报关方式'},
  {dataIndex: '', title: '清关方式'},
  {dataIndex: '', title: '带电'},
  {dataIndex: '', title: '带磁'},
  {dataIndex: '', title: '承运'},
  {dataIndex: '', title: '自定义标识'},
  {dataIndex: '', title: '主品名'},
  {dataIndex: 'depot_id', title: '货站', dict: dictHelp.depot, formType: 'select', search: true},
  {dataIndex: 'info.remark', title: '备注'},
  {dataIndex: 'picking_at', title: '拣货时间', search: true, formType: "range",},
  {dataIndex: 'created_at', title: '下单时间', search: true, formType: "range",hide:true},
]
const statistics = ref({
  shipment_count: 0,
  weight: 0,
  volume: 0,
  volume_weight: 0,
  box_count: 0,
  charge_weight: 0,
})
const parcelListRef = ref()
const options = reactive({
  id: 'addToWaybill',
  rowSelection: {
    showCheckedAll: true
  },
  isDbClickEdit: true,
  pk: 'id',
  formOption: {
    // stickyHeader:true,
    viewType: 'drawer',
    width: '80%',
    // layout: [
    //   {
    //     formType: 'grid-tailwind',
    //     colNumber: 2,
    //     cols: [
    //       {
    //         formList: [
    //           {dataIndex: "user_id"},
    //           {dataIndex: "shipment_no"},
    //           {dataIndex: "client_reference"},
    //           {dataIndex: "service_id"},
    //           {dataIndex: "address_lib_detail_id"},
    //           {dataIndex: 'name'},
    //           {dataIndex: 'company'},
    //           {dataIndex: 'address1'},
    //           {dataIndex: 'address2'},
    //           {dataIndex: 'address3'},
    //           {
    //             formType: 'card',
    //             bordered: false,
    //             customClass: ['form-inline-card'],
    //             size: 'small',
    //             title: null,
    //
    //             // commonRules: {
    //             //   required: true,
    //             //   message: "请选择用户"
    //             // },
    //             formList: [
    //               {dataIndex: 'city', title: '城市'},
    //               {dataIndex: 'state', title: '州/省'},
    //               {dataIndex: 'postcode', title: '邮编'},
    //             ]
    //           },
    //           {dataIndex: 'country'},
    //           {dataIndex: 'phone'},
    //           {dataIndex: 'email'},
    //         ]
    //       },
    //       {
    //         formList: [
    //           {dataIndex: "self_reference"},
    //           {dataIndex: "reference_1"},
    //           {dataIndex: "reference_2"},
    //           {dataIndex: "attrs"},
    //           {dataIndex: "picking_at"},
    //           {dataIndex: "delivered_at"},
    //           {dataIndex: "seller_id"},
    //           {dataIndex: "finance_id"},
    //           {dataIndex: "organization_id"},
    //           {dataIndex: "customer_service_id"},
    //           // {dataIndex: "top"},
    //           {dataIndex: "declaration_currency"},
    //           {dataIndex: "ext_number"},
    //           {dataIndex: "po_number"},
    //           {dataIndex: "depot_id"},
    //           {dataIndex: "taxwith"},
    //           {dataIndex: "deliverywith"},
    //           {dataIndex: "exportwith"},
    //           {dataIndex: "importwith"},
    //           {dataIndex: "vat_number"},
    //           {dataIndex: "ioss"},
    //           {dataIndex: "eori"},
    //           {dataIndex: "internal_remark"},
    //           {dataIndex: "remark"},
    //           // {dataIndex: "waybill_id"},
    //         ]
    //       },
    //     ]
    //   },
    // ]
  },
  api: shipment.getList,
  requestParams: {
    'scence': 'distribution',
    keep_tab: 1,
    orderBy: 'picking_at',
    orderType: 'desc',
  },
  edit: {
    auth: [],
    show: true,
    api: () => {
    },
    action: (record) => {
      parcelListRef.value.open(record)
      // show.value = true
    }
  }
})
const notification = getCurrentInstance().appContext.config.globalProperties.$notification;
const selected = computed(() => crudRef.value?.selecteds)
const addToWaybill = () => {
  batchActionRef.value.open({
    title: '放入提单',
    api: waybill.addParcelById,
    displayDataIndex: "shipment_no",
    form: {
      key: 'shipment',
      columns: [
        {
          dataIndex: 'waybill_id',
          title: '提单号',
          formType: 'select',
          dict: Object.assign(dictHelp.waybillShouldSelect, {}),
          rules: {
            required: true,
            message: "请选择提单"
          },
        }
      ]
    }
  })
}
onBeforeRouteLeave(() => {
  statistics.notify && statistics.notify.close()
})
watch(() => selected,
    (v) => {
      if (!v.value || v.value.length === 0) {
        statistics.notify && statistics.notify.close()
        return;
      }
      console.log(selected.value)
      const records = crudRef.value.getTableData().filter(i => selected.value.indexOf(i.id) > -1)
      console.log(records)
      console.log('notification',notification)

      statistics.value = {
        shipment_count: selected.value.length,
        weight: records.reduce((acc, cur) => acc + Number(cur.volume_weight.actual_weight), 0),
        volume: records.reduce((acc, cur) => acc + Number(cur.volume_weight.actual_volume), 0),
        volume_weight: records.reduce((acc, cur) => acc + Number(cur.volume_weight.actual_volume_weight), 0),
        box_count: records.reduce((acc, cur) => acc + Number(cur.volume_weight.parcel_count), 0),
        // charge_weight: records.reduce((acc, cur) => acc + Number(cur.volume_weight.parcel_count), 0),
      }
      statistics.notify = notification.warning({
        id: 'addToWaybillStatistics',
        // title: 'Title', // (KG) (m³)
        content: <div class="grid grid-cols-3 gap-2">
          <span>票数:{statistics.value.shipment_count}</span>
          <span>实重:{statistics.value.weight.toFixed(2)}</span>
          <span>材重:{statistics.value.volume_weight.toFixed(2)}</span>
          <span>箱数:{statistics.value.box_count}</span>
          <span>体积:{statistics.value.volume.toFixed(2)}</span>
        </div>,
        //
        // <span>收费重:{statistics.value.charge_weight}</span>
        position: "bottomLeft",
        duration: 0,
        class: ['bg-red-400 p-1'],
        style: {
          width: '30vw'
        },
        showIcon: false
      })
    },
    {deep: true,}
)
</script>
<script lang="jsx"> export default {name: 'document:waybill:addParcel'} </script>
<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #shipment_no="{ record }">
        <a-link color="blue" @click="crudRef.editAction(record)">{{ record.shipment_no }}</a-link>
      </template>
      <template #tableAfterButtons>
        <a-button type="primary" @click="addToWaybill">放入提单</a-button>
      </template>
    </ma-crud>
    <batch-action-modal
        :crud-ref="crudRef"
        :selected="selected"
        ref="batchActionRef"
    ></batch-action-modal>
    <parcelList ref="parcelListRef"/>
  </div>
</template>

<style scoped>

</style>